<template>

    <div style="margin: 20px 10px; height: 500px;">
        <a-row :gutter="[10,0]">
            <a-col :span="4">
                <div style="background-color: white; height: 500px">
                    <div class="chooseByAreaBox">
                        <span class="chooseByArea" style="font-weight: 600">按区域筛选</span>
                    </div>

                    <hr>
                    <div class="area-list">
                        <a-tree
                            v-if="provinces.length > 0"
                            :selected-keys="selectedKeys"
                            :tree-data="provinces"
                            default-expand-all
                            @select="onSelect">
                            <template #title="{ title, key }">
                                <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
                                <template v-else>{{ title }}</template>
                            </template>
                        </a-tree>
                    </div>
                </div>
            </a-col>


            <a-col span="20" style="height: 500px;">
                <a-card size="default" title="按区域统计总时长">
                    <a-row>
                        <a-col span="16">
                            <a-range-picker
                                v-model="searchDateRange"
                                :ranges="{ '今天': [moment().startOf('day'), moment()], '本月': [moment().startOf('month'), moment()] }"
                                show-time size="default"
                                style="margin-right: 6px"/>

                            <a-select :filter-option="filterOption"
                                      allowClear
                                      placeholder="电子标签编号"
                                      show-search
                                      style="width: 150px"
                                      @change="(value)=>{selectIndex=value;onShowSizeChange()}">
                                <a-select-option v-for="(item,index) in mecnos" :key="index"
                                                 placeholder="请选择环保编码">
                                    {{ item }}
                                </a-select-option>
                            </a-select>


                            <a-button style="margin-left: 6px" type="primary" :loading="btnLoading"
                                      @click="onShowSizeChange">统计
                            </a-button>
                        </a-col>

                        <a-col offset="6" span="2">
                            <a-button @click="exportData">
                                <a-icon type="upload"></a-icon>
                                导出
                            </a-button>

                        </a-col>
                    </a-row>

                    <a-table :columns="[{title:'电子标签编号', key:'name', dataIndex:'name'},
                            {title: '总时长', key:'total', dataIndex: 'total',
                                scopedSlots: {customRender: 'total'}}]"
                             :data-source="data"
                             :pagination="false"
                             rowKey="name" style="margin-top: 10px">
                        <span slot="total" slot-scope="total">
                            {{ total + ' 小时' }}
                        </span>
                    </a-table>

                </a-card>
            </a-col>
        </a-row>


    </div>
</template>

<script>
import fileDownload from 'js-file-download';
import {operation1, operation2, operation3, operationColumns} from '@/mock/common/tableData'
import {mapState} from 'vuex'
import {METHOD, request, RESPONSE} from "@/utils/request";
import moment from "moment";


export default {
    name: 'AdvancedDetail',
    data() {
        return {
            moment,
            searchDateRange: [],
            selectedKeys: [],
            provinces: [],
            data: [],
            operationColumns,
            operation1,
            operation2,
            operation3,
            activeTabKey: '2',
            mecnos: [],  // 机械编号列表
            selectIndex: null,  // 选中要查询的电子标签编号
            btnLoading: false,
        }
    },
    computed: {
        ...mapState('setting', ['isMobile'])
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        this.refreshList();
        // this.getWorkTimeStatistic();
    },
    methods: {
        filterOption(input, option) {
            return (
                // 过滤忽略大小写
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        exportData() {
            let levelAndKey = this.onShowSizeChange(false);
            request("/position/getWkhrExe", METHOD.POST, null, {
                params: {
                    id: this.userID,
                    sel_key: levelAndKey[0],
                    sel_level: levelAndKey[1],
                    stime: this.searchDateRange.length === 2 ? parseInt(moment(this.searchDateRange[0]).valueOf() / 1000) : null,
                    endtime: this.searchDateRange.length === 2 ? parseInt(moment(this.searchDateRange[1]).valueOf() / 1000) : null
                },
                responseType: 'blob'
            }).then(res => {

                fileDownload(res.data, '测试.xlsx');

            });
        },
        // 点击选择了一个区域
        onSelect(selectedKeys, info) {
            console.log(selectedKeys);
            this.selectedKeys = selectedKeys;
            console.log('onSelect', info);
            // 查找选择节点的key和层级
            let keyAndLevel = this.onShowSizeChange(false);
            // 更新下拉框的可选机械标签值
            this.getMachineInfoByArea(keyAndLevel)
        },
        getMachineInfoByArea(levelAndKey) {
            request("/position/getDzbqByqy", METHOD.GET, {
                id: this.userID,
                sel_level: levelAndKey[0],
                sel_key: levelAndKey[1]
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.mecnos = ["所有"].concat(res.data.data);
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        findAreaByKey(area, key) {

            if (area.children != null && area.children.length > 0) {
                // 有子节点查询所有的子节点
                for (let i = 0; i < area.children.length; i++) {
                    let result = this.findAreaByKey(area.children[i], key);
                    if (result != null) {
                        // 找到了直接返回结果
                        return result;
                    }
                }
            }

            // 没有子节点 或者子节点查完了，检查本身节点
            if (area.key === key) {
                // 找到了直接返回结果
                return area;
            } else {
                // 告诉父节点没找到，继续找
                return null;
            }

        },
        onShowSizeChange(needGetData = true) {
            let area = null;
            // 查找当前选中的层级
            if (this.selectedKeys.length !== 0) {
                // 左侧区域选中了层级就查询这个层级的设备
                for (let i = 0; i < this.provinces.length; i++) {
                    area = this.findAreaByKey(this.provinces[i], this.selectedKeys[0]);
                    if (area != null) {
                        // 找到了，需要请求就发送请求结束
                        if (needGetData) {
                            this.getWorkTimeStatistic(area.level, this.selectedKeys[0])
                        }

                        return [area.level, this.selectedKeys[0]];
                    }
                }
            } else {
                // 左侧区域没选择就查询所有的设备
                if (needGetData) {
                    this.getWorkTimeStatistic(null, null);
                }
                return [null, null];
            }
        },
        refreshList() {
            request("/areas/getAreas?id=" + this.userID, METHOD.GET).then(result => {
                if (result.data.code === 1) {
                    this.provinces = result.data.data;
                    // 默认选择最大的区域
                    this.selectedKeys = [this.provinces[0].children[0].children[0].key];


                    this.getMachineInfoByArea([3, this.provinces[0].children[0].children[0].key]);
                } else {
                    this.$message.error(result.data.msg);
                }
            })
        },
        onTabChange(key) {
            console.log(key)
        },
        // 工作时长统计
        getWorkTimeStatistic(sel_level, sel_key) {

            if (this.searchDateRange.length !== 2) {
                this.$message.error("请选择日期,在查询");
                return
            }

            this.btnLoading = true;

            request("/position/getTbwk", METHOD.GET, {
                // 选中了区域 && 下拉选择了查询所有
                input: (sel_key != null && this.selectIndex === 0) ? sel_key : this.mecnos[this.selectIndex],  // 机械标签 or 区域的key
                userid: this.userID,
                sel_key: sel_key,
                sel_level: sel_level,
                startime: this.searchDateRange.length === 2 ? parseInt(moment(this.searchDateRange[0]).valueOf() / 1000) : null,
                endtime: this.searchDateRange.length === 2 ? parseInt(moment(this.searchDateRange[1]).valueOf() / 1000) : null,
                state: (sel_key != null && this.selectIndex === 0) ? 1 : null
            }).then(res => {

                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.data.length = 0;

                    Object.keys(res.data.data).forEach((key) => {
                        this.data.push({
                            "name": key,
                            "total": res.data.data[key],
                        })

                    })
                } else {
                    this.$message.error(res.data.msg);
                }

                this.btnLoading = false;
            });
        }
    },
}
</script>

<style lang="less" scoped>
</style>
